﻿package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.umeng.analytics.MobclickAgent;

public class PersonalInfoPhoneNumberSettingActivity extends WuyangBaseActivity {
	protected static final int please_auth_code_number = 0;
	protected static final int please_auth_code_wenzi = 1;
	private Button back_btn;
	private Button submit_btn;
	private String createAuthCode = "22";
	private EditText phone_nubmer_et;
	private EditText auth_code_et;
	private String phone_nubmer;
	private String auth_code;
	private TextView please_auth_code;
	public static int phone_number_flag  = 0; 
	
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
							com.alibaba.fastjson.JSONObject jsonObjectResult= JSON.parseObject(result);
							if(null != jsonObjectResult.getString("randomCode")){
								String jsonStr = jsonObjectResult.getString("randomCode");
								createAuthCode = jsonStr;
								finishProgress();
							}/*else {
//								showToast("成功");
								Intent intent = new Intent();
								intent.putExtra("phone_nubmer", phone_nubmer);
								setResult(255, intent);
//								phone_number_flag = 200;
								finish();
							}		*/					
							
						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							showToast(StringUtil.geterrorMsg(result));
						}
					} catch (JSONException e) {
						finishProgress();
						showToast("失败");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	protected JSONObject jsonObjectResult;
	Handler handler_UPDATE_MOBILE = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
								jsonObjectResult= JSON.parseObject(result);
								Intent intent = new Intent();
								intent.putExtra("phone_nubmer", phone_nubmer);
								setResult(255, intent);
//								phone_number_flag = 200;
								finish();
						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							showToast(jsonObjectResult.getString("errorMsg"));
						}
					} catch (JSONException e) {
						finishProgress();
						showToast("失败");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	
	Handler message_handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case please_auth_code_number:
				please_auth_code.setText(times+"秒后可再次发送");
				break;

			case please_auth_code_wenzi:
				please_auth_code.setText("请求验证码");
				please_auth_code.setClickable(true);
				break;
			}
			super.handleMessage(msg);
		}
		
	};
	private int userId;
	private int times = MainConstants.TIMES;

	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.personal_info_phone_number_setting) ;
		super.onCreate(savedInstanceState);
		this.setHeaderControlViewText();
		this.initBodyControlView();
		this.registerListener();
		userId = SharePrefenceUtil.getUserID(this);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.header_left:
			this.finish();
			break;
		case R.id.please_auth_code://发送短信验证码
			//showToast("模拟发送验证码");
			/*StringUtil stringUtil = new StringUtil();
			createAuthCode = stringUtil.createAuthCode();
			SendSmsUtil sendSmsUtil = new SendSmsUtil(this);
			sendSmsUtil.sendSms("15226160897", createAuthCode);*/
			this.getControlViewText();
			if(null ==phone_nubmer ||"".equals(phone_nubmer)||!isPhoneNum(phone_nubmer)){
				showToast("手机号不正确");
				break;
			}else{
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("mobileNumber",phone_nubmer));
				params.add(new BasicNameValuePair("userId",userId+""));
				params.add(new BasicNameValuePair("email",null));
				new DataLoader(this).DisplayData(MainConstants.HOST_test+HttpConfigAPI.RANDOM_CODE, params , handler, "", false);
				please_auth_code.setClickable(false);
					new Timer().schedule(new TimerTask() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							if(times > 0){
								times --;
								message_handler.sendEmptyMessage(please_auth_code_number);
								
							}else {
								message_handler.sendEmptyMessage(please_auth_code_wenzi);
								times = MainConstants.TIMES ;
								this.cancel();
							}
						}
					}, 1000, 1000);
				
				/*new Handler().postDelayed(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						please_auth_code.setClickable(true);
					}
				},MainConstants.TIME);*/
				showProgress("正在加载数据...");
			}
			break;
		case R.id.header_right:
			this.getControlViewText();
			if(null ==phone_nubmer ||"".equals(phone_nubmer)||!isPhoneNum(phone_nubmer)){
				showToast("手机号不正确");
				break;
			}
			if(null ==auth_code||"".equals(auth_code)){
				showToast("验证码未输入");
				break;
			}
			if(!auth_code.equals(createAuthCode)){
				showToast("验证码错误！");
				break;
			}
			//向服务器提交修改信息
			//showToast("向服务器提交修改信息"+phone_nubmer+"----"+auth_code);
			
			List<NameValuePair> params1 = new ArrayList<NameValuePair>();
			params1.add(new BasicNameValuePair("mobileNumber",phone_nubmer));
			params1.add(new BasicNameValuePair("userId",userId+""));
			params1.add(new BasicNameValuePair("randomCode",createAuthCode));
			new DataLoader(this).DisplayData(MainConstants.HOST_test+HttpConfigAPI.UPDATE_MOBILE, params1 , handler_UPDATE_MOBILE, "", false);
			showProgress("正在加载数据...");
			break;
		default:
			break;
		}
	}

	@Override
	protected void setHeaderControlViewText() {
		super.setHeaderTitleText(headerTitle, "手机号码");
		super.setHeaderLeftText(headerLeft, "返回");
		super.setHeaderRightText(headerRight, "提交");
	}

	@Override
	protected void initBodyControlView() {
		back_btn = (Button)this.findViewById(R.id.header_left);
		please_auth_code = (TextView)this.findViewById(R.id.please_auth_code);
		submit_btn = (Button)this.findViewById(R.id.header_right);
		phone_nubmer_et = (EditText)this.findViewById(R.id.phone_nubmer);
		auth_code_et = (EditText)this.findViewById(R.id.auth_code);
	}

	@Override
	protected void registerListener() {
		back_btn.setOnClickListener(this);
		please_auth_code.setOnClickListener(this);
		submit_btn.setOnClickListener(this);
	}

	@Override
	protected void setBodyControlViewText() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void getControlViewText() {
		// TODO Auto-generated method stub
		phone_nubmer = phone_nubmer_et.getText().toString();
		auth_code = auth_code_et.getText().toString();
	}
}
